package com.demo.webapp.kcfinder.utils;

import java.io.Serializable;
import java.util.Map;

import org.mvel.MVEL;
import org.mvel.ParserContext;

/**
 * Mvel值栈
 * 
 * @author ryuu.kk
 *
 */
public class MvelValueStack implements ValueStack{

	transient Map<String, Object> context;
	
	@Override
    public Map<String, Object> getContext() {
        return context;
    }

	public MvelValueStack() {
		context = new ValueContext();
	}
	
	public MvelValueStack(Map<String, Object> params) {
		context = new ValueContext(params);
	}
	
	@Override
	public void setValue(String expr, Object value) {
		context.put(ValueStack.CONVERSION_PROPERTY_FULLNAME, expr);
		setValue(expr, value, false);
	}

	@Override
	public void setValue(String expr, Object value, boolean throwExceptionOnFailure) {
		//设置强类型
		//ctx.addImport(name, cls);
		String expression = expr;
		try {
			//创建分析器上下文
			ParserContext ctx = new ParserContext();
			Serializable ce = MVEL.compileExpression(expression, context);
		} catch (Exception e) {
			if (throwExceptionOnFailure) {e.printStackTrace();}
		}
		
		context.put(expression, value);
	}

	@Override
	public Object findValue(String expr) {
		return findValue(expr, false);
	}

	@Override
	public Object findValue(String expr, boolean throwExceptionOnFailure) {
		String expression = expr;
		Serializable compiled = MVEL.compileExpression(expression);
        // Now we execute it.
        Object result = null;
        try {
			result = MVEL.executeExpression(compiled, context);
		} catch (Exception e) {
			if (throwExceptionOnFailure) {
				e.printStackTrace();
			}
		}
		return result;
	}

	@Override
	public Object peek() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object pop() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void push(Object o) {
		// TODO Auto-generated method stub
	}
}
